﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Globalization;
using System.Windows.Forms;
using DSPL.Contracts;
using DSPL.Contracts.Common;
using DSPL.Contracts.Interfaces;
using System.Diagnostics;
using DSPL.DataAccess;
using DSPL.Services.Services;
using DSPL.DataAccess.MasterData;

namespace DSPL.Services.Rules
{
    public class CommonRules : ICommonRules
    {  
        public decimal GetLatestCurrencyRate(string currencyCode, string baseCurrency, DateTime transactionDate)
        {
            if (currencyCode == string.Empty)
            {
                return 0.00M;
            }

            if (baseCurrency == string.Empty)
            {
                return 0.00M;
            }

            var db = DatabaseAccess.Instance;
                      
            List<ParameterWithValue> paramList = new List<ParameterWithValue>();

            paramList.Add(new ParameterWithValue("@vchCurrencyCode", currencyCode));
            paramList.Add(new ParameterWithValue("@vchBaseCurCode", baseCurrency));
            paramList.Add(new ParameterWithValue("@dateTransactionDate", transactionDate));
            paramList.Add(new ParameterWithValue("@curRate", 0.00,SqlDbType.Decimal,ParameterDirection.ReturnValue));
            SpCaller spCaller = new SpCaller() { SpName = "GetLatestCurrencyRate", SpParamValues = paramList.ToArray() };
                      
            return (decimal)(db.Excecute(spCaller, "@curRate"));          
           
        }
               
        
        public double ValidateCurrencyRate(string currencyName, double curerencyRate)
        {
            return 0.00;
        }

        public bool ValidateUserRights(string costcode="",string locationCode="")
        {           
            var db = DatabaseAccess.Instance;

            List<ParameterWithValue> paramList = new List<ParameterWithValue>();

            paramList.Add(new ParameterWithValue("@vchCostCode", costcode));
            paramList.Add(new ParameterWithValue("@vchLocCode", locationCode));
            paramList.Add(new ParameterWithValue("@vchUser", GlobalVariables.LoggedInUser));
            paramList.Add(new ParameterWithValue("@vchMessage", "",SqlDbType.VarChar, ParameterDirection.Output));   
            paramList.Add(new ParameterWithValue("@result", true, SqlDbType.Bit , ParameterDirection.ReturnValue));
            SpCaller spCaller = new SpCaller() { SpName = "ValidateUserRights", SpParamValues = paramList.ToArray() };
            return (bool)(db.Excecute(spCaller, "@result"));
            
        }


        /// <summary>
        ///  Multiple Line Tax Calculation
        /// </summary>
        /// <param name="dtTranDet">Transaction Detail table (Temporary)</param>
        /// <param name="dtTaxDetailTable">Tax transaction table</param>
        /// <param name="curRate"> Currency exchange rate</param>
        /// <param name="taxDetailTranTable"> Link Transaction Tax Detail Table (Leave Blank to pick tax from Tax detail table) </param>
        /// <param name="taxRegState"></param>
        /// <param name="totalTax">out parameter to get the Total Tax Amount</param>
        /// <param name="totAmount">out parameter to get the Total Amount</param>
        /// <param name="referenceNo">Link Transaction Reference No (Leave Blank if multiple references (Grid Fields “RefNo1”) OR Reference No to pick Tax details)</param>
        /// <param name="whereCondition">Record Validation (To check valid line records)</param>
        /// <param name="keyFields">Tax transaction table key fields (Support multiple character type fields OR Leave blank for if key field is not required)</param>
        /// <param name="isTaxReverse"> Reverse Tax Flag (true – Reverse, false – Forward Calculation)   </param>
        /// <returns>Update some out parameters and return true or false</returns>
        public bool MultipleLineTaxCalculation(ref DataTable dtTranDet, ref DataTable dtTaxDetailTable, double curRate,
            out double totalTax, out double totAmount, int taxRegState = 0, int referenceNo = 0, string taxDetailTranTable = "", string whereCondition = "", string keyFields = "", int refNoValue=0, bool isTaxReverse = false)
        {
            totalTax = totAmount = 0.00;

            if (dtTranDet == null)
            {

                return false;
            }

            if (dtTaxDetailTable == null)
            {

                return false;
            }

            if (referenceNo != 0)
            {
                if (taxDetailTranTable == string.Empty)
                {

                    return false;
                }
            }

            string[] keyFieldList = null;

            bool isSuccess = true;
            double totalTaxAmount, sumTotalTaxAmount, totalAmount, amount;

            DataRow[] transactions = dtTranDet.Select(whereCondition);
            string taxComCode = "";
            totalTaxAmount = sumTotalTaxAmount = totalAmount = amount = 0.00;
            if (keyFields != string.Empty)
            {
                keyFieldList = keyFields.Split(',');
            }
            
            List<ParameterWithValue> paramList = new List<ParameterWithValue>();

            paramList.Add(new ParameterWithValue("@tranDetail",dtTranDet, SqlDbType.Structured ));
            paramList.Add(new ParameterWithValue("@taxDetail", dtTaxDetailTable, SqlDbType.Structured));                    
            paramList.Add(new ParameterWithValue("@curRate", curRate));
            paramList.Add(new ParameterWithValue("@totalTax", totalTax, SqlDbType.Float, ParameterDirection.Output));
            paramList.Add(new ParameterWithValue("@totAmount", totAmount, SqlDbType.Float, ParameterDirection.Output));
            paramList.Add(new ParameterWithValue("@taxRegState", taxRegState ));
            paramList.Add(new ParameterWithValue("@referenceNo", referenceNo));
            paramList.Add(new ParameterWithValue("@taxDetailTranTable", taxDetailTranTable));
            paramList.Add(new ParameterWithValue("@whereCondition", whereCondition));
            paramList.Add(new ParameterWithValue("@keyFields", keyFields));           
            paramList.Add(new ParameterWithValue("@refNoValue", refNoValue));  
            paramList.Add(new ParameterWithValue("@isTaxReverse", isTaxReverse));
            paramList.Add(new ParameterWithValue("@userName", GlobalVariables.LoggedInUser));          
            paramList.Add(new ParameterWithValue("@result", 1, SqlDbType.Bit, ParameterDirection.Output));
            paramList.Add(new ParameterWithValue("@message", "", SqlDbType.VarChar, ParameterDirection.Output, 5000));
            

            SpCaller spCaller = new SpCaller() { SpName = "stock.MULTILINE_TAX_CAL", SpParamValues = paramList.ToArray() };
            var db = DatabaseAccess.Instance;
            Dictionary<string, object> result = (Dictionary<string, object>)(db.ExcecuteMultipleOutputParameters(spCaller));

             foreach (KeyValuePair<string, object> outputParam in result)
            {
                if (outputParam.Key == "@totalTax")
                {
                    totalTax = (outputParam.Value==DBNull.Value?0.00 :(double)outputParam.Value);
                }

                if (outputParam.Key == "@totAmount")
                {
                    totAmount = (outputParam.Value==DBNull.Value?0.00 :(double)outputParam.Value);
                }

                if (outputParam.Key == "@message")
                {
                    if (outputParam.Value.ToString() != string.Empty)
                    {
                        MessageBox.Show(outputParam.Value.ToString(), "Stock Rules", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                }
            }
            return true;
        }
    }
       
       
       
    
}
